package com.deer.wms.base.system.web.bill;


import com.deer.wms.base.system.model.bill.*;
import com.deer.wms.base.system.model.item.ItemInfo;
import com.deer.wms.base.system.model.ware.Supplier;
import com.deer.wms.base.system.service.bill.BillOutSapService;
import com.deer.wms.base.system.service.bill.IBillOutMasterService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.item.IItemInfoService;
import com.deer.wms.base.system.service.zh.WorkTasksService;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.deer.wms.framework.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**SAP出库单据*/
@Controller
@RequestMapping("/out/billOutSap")
public class BillOutSapController extends BaseController {

    private String prefix = "out/billOutSap";

    @Autowired
    private BillOutSapService billOutSapService;
    @Autowired
    private IBillOutMasterService billOutMasterService;
    @Autowired //物料
    private IItemInfoService itemInfoService;
    @Autowired //工作任务
    private WorkTasksService workTasksService;
    @Autowired //库存
    private IBoxItemService boxItemService;

    /*跳转明细列表*/
    @GetMapping("/billOutSapTakePage")
    public String billOutSapDetail() {
        return prefix + "/billOutSapTakePage";
    }
    /*跳转明细查看*/
    @GetMapping("/billOutSapDeatil")
    public String billOutSapDeatil() {
        return prefix + "/billOutSapDeatil";
    }

    @GetMapping("/billOutSapPageDeatil")
    public String billOutSapPageDeatil() {
        return prefix + "/billOutSapPageDeatil";
    }


    /*SAP出库单明细列表*/
    @PostMapping("/detailList")
    @ResponseBody
    public TableDataInfo detailList(BillOutSapDetailDto billOutSapDetailDto) {
        startPage();
        List<BillOutSapDetailDto> billOutSapDetailList = billOutSapService.findBillOutSapDetailList(billOutSapDetailDto);
        return getDataTable(billOutSapDetailList);
    }
    /*删除单据*/
    @PostMapping( "/detele")
    @ResponseBody
    @Transactional
    public AjaxResult remove(Integer id) {
        return toAjax(billOutSapService.deleteSapByIds(id)+billOutSapService.deleteSapDetailByIds(id));
    }

    /*SAP出库单列表*/
    // @RequiresPermissions("in:billInSap:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BillOutSap billOutSap) {
        startPage();
        List<BillOutSap> billOutSapList = billOutSapService.findBillOutSapList(billOutSap);
        return getDataTable(billOutSapList);
    }

    /*根据id找sap单*/
    @PostMapping("/findBillOutSapByBillOutSapId")
    @ResponseBody
    public BillOutSapDto findBillOutSapByBillOutSapId(Integer billOutSapId){
        return billOutSapService.findBillOutSapByBillOutSapId(billOutSapId);
    }

    /*根据id找sap单明细*/
    @PostMapping("/findBillOutSapDetailByBillOutSapId")
    @ResponseBody
    public TableDataInfo findBillOutSapDetailByBillOutSapId(Integer billOutSapId){
        List<BillOutSapDetailDto> list = billOutSapService.findBillOutSapDetailByBillOutSapId(billOutSapId);
        return getDataTable(list);
    }


    /*审核跳转*/
    @GetMapping("/billOutSapAudit")
    public String billOutSapAudit() {
        return prefix + "/billOutSapAudit";
    }
    /*手工建单审核跳转*/
    @GetMapping("/billOutSapAuditManual")
    public String billOutSapAuditManual() {
        return prefix + "/billOutSapAuditManual";
    }
    /*手工建单的审核提交*/
    @PostMapping("/auditManual")
    @ResponseBody
    @Transactional
    public Result auditSaveManual(@RequestBody BillOutSap billOutSap) {
        //添加SAP采购单
        billOutSap.setBillState(2); //已审核
        billOutSapService.updateBillOutSap(billOutSap);
        String createUserName = ShiroUtils.getLoginName();
        billOutSap.setCreateName(createUserName);
        billOutMasterService.updateSapNoBySapId(billOutSap);//入库单

        return ResultGenerator.genSuccessResult();
    }

    /*审核提交*/
    @PostMapping("/audit")
    @ResponseBody
    @Transactional
    public Result auditSave(@RequestBody BillOutSap billOutSap) {
        //改变sap单状态 已审核
        billOutSap.setBillState(2);
        billOutSapService.updateBillOutSap(billOutSap);
        //创建出库单
        //插入数据准备
        Long outNumber = workTasksService.getBillOutNumber();
        String billNo = "JH" + outNumber;
        String createUserName = ShiroUtils.getLoginName();
        Integer userId = ShiroUtils.getUserId();
        BillOutMaster billOutMaster = new BillOutMaster();
        billOutMaster.setState(1)//1待出库
                .setSapState(1) //过账
                .setBillNo(billNo)
                .setOutNumber(outNumber)
                .setType(billOutSap.getType())
                .setSapNo(billOutSap.getSapNo())
                .setSapId(billOutSap.getBillOutSapId())
                .setCreateUserName(createUserName)
                .setAuditUserId(userId)
                .setAuditUserName(createUserName);
        billOutSapService.insertBillOutMaster(billOutMaster);

        return ResultGenerator.genSuccessResult();
    }

    /*下载SAP模板*/
    @GetMapping("/importTemplate")
    @ResponseBody
    @Transactional
    public AjaxResult importTemplate(){
        List<BillOutSapDto> billOutSapList =new ArrayList<>();
        BillOutSapDto b=new BillOutSapDto();
        billOutSapList.add(b);
        ExcelUtil<BillOutSapDto> util = new ExcelUtil<BillOutSapDto>(BillOutSapDto.class);

        return util.importTemplateExcel(billOutSapList,"SAP出库单模板");
    }

    /*导入SAP模板*/
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BillOutSapDto> util = new ExcelUtil<BillOutSapDto>(BillOutSapDto.class);
        List<BillOutSapDto> List = util.importExcel(file.getInputStream());
        //java.util.List<BillOutSapDto> electricBoxDetails = List.subList(2, List.size());

        String userName = ShiroUtils.getLoginName();
        Integer userId = ShiroUtils.getUserId();
        BillOutSapDto billOutSapDto = List.get(2);
        //新建SAP出库单
        billOutSapDto.setCreateName(userName)
                .setCreateId(userId)
                .setBillState(1).setState(1);
        billOutSapService.insertBillOutSap(billOutSapDto);

        //添加SAP出库明细
        List.forEach(sapDetail->{
            if(sapDetail.getType() != null){
                System.out.println(sapDetail);
                ItemInfo ItemInfo = itemInfoService.findByItemCode(sapDetail.getMATNR());
                sapDetail.setItemId(ItemInfo.getItemId())
                        .setState(1)
                        .setBillOutSapId(billOutSapDto.getBillOutSapId());
                billOutSapService.insertBillOutSapDetail(sapDetail);
            }
        });

        return AjaxResult.success("导入成功");
    }
    /*根据id强制过账*/
    @PostMapping("/sapPosting")
    @ResponseBody
    @Transactional
    public AjaxResult posting(@RequestBody BillOutSap billOutSap) {
        int billOutSapId = billOutSap.getBillOutSapId();
        //1.查询所有未过账id
        List<Integer> idList = billOutSapService.findStateDetailById(billOutSapId);
        //2.拼接成str字符串
        String ids="";
        for (Integer id : idList) {
            ids = ids+id+",";
        }

        List<BillOutSapDetailVo> byIds = new ArrayList();
        BillOutSapDetailVo billOutSapDetailVo = new BillOutSapDetailVo();
        SimpleDateFormat batchDate = new SimpleDateFormat("yyyyMMdd");
        String batchDay = batchDate.format(new Date());
        int id = 0;
        int sum = 0;
        String[] split = ids.split(",");
        for (String s:split) {
            id = Integer.parseInt(s);
            BillOutSapDetailDto BillOutSapDetail = billOutSapService.findBillOutSapDetailVo(id);
            billOutSapDetailVo.setMtsnr(batchDay)//当前日期
                    .setMatnr(BillOutSapDetail.getMATNR())//物料号
                    .setErfmg(BillOutSapDetail.getERFMG_RECEIVED()) //重量
                    .setErfme(BillOutSapDetail.getERFME())//单位
                    .setLgort("R003")
                    .setCharg(batchDay);
                    //.setKostl(BillOutSapDetail.getKOSTL());//成本中心
            byIds.add(billOutSapDetailVo);
            //修改状态为已过帐
            billOutSapService.updateDetailCarryStateById(id);
            //判断如果全部都过账,则SAP单已过帐
            sum = billOutSapService.selectCarryStateCount(id);
            if(sum != 0){
                billOutSapService.updateBillInSapState3(id); //部分
            }else {
                billOutSapService.updateBillInSapState2(id); //已过账
            }
        }
        ExcelUtil<BillOutSapDetailVo> util = new ExcelUtil<>(BillOutSapDetailVo.class);
        return util.exportExcel(byIds, "SAP出库过账单据");

    }

    /*导出SAP,并改变过账状态为过账*/
    @PostMapping("/partExcel")
    @ResponseBody
    @Transactional
    public AjaxResult partExcel(@RequestParam  String ids) {
        List<BillOutSapDetailVo> byIds = new ArrayList();
        SimpleDateFormat batchDate = new SimpleDateFormat("yyyy/MM/dd");
        String batchDay = batchDate.format(new Date());
        SimpleDateFormat batchN = new SimpleDateFormat("yyyyMMdd");
        String batchNumber = batchN.format(new Date());
        int id = 0;
        int sum = 0;
        String[] split = ids.split(",");
        for (String s:split) {
            id = Integer.parseInt(s);
            BillOutSapDetailDto BillOutSapDetail = billOutSapService.findBillOutSapDetailVo(id);
            BillOutSapDetailVo billOutSapDetailVo = new BillOutSapDetailVo();
            billOutSapDetailVo.setBudat(batchDay)//过账日期
                    .setBldat(BillOutSapDetail.getCreateTime())//凭证日期
                    .setBwartwa("311")//移动类型
                    .setWerks(1000)//工厂
                    .setLgort("L003")
                    .setWvers("X")
                    .setUmlgo("R003")
                    .setMatnr(BillOutSapDetail.getMATNR())//物料号
                    .setErfmg(BillOutSapDetail.getERFMG_RECEIVED()) //重量
                    .setErfme(BillOutSapDetail.getERFME())//单位
                    .setCharg(batchNumber);
                    //.setKostl(BillOutSapDetail.getKOSTL());//成本中心
            byIds.add(billOutSapDetailVo);
            //修改状态为已过帐
            billOutSapService.updateDetailCarryStateById(id);
            //判断如果全部都过账,则SAP单已过帐
            sum = billOutSapService.selectCarryStateCount(id);
            if(sum != 0){
                billOutSapService.updateBillInMasterState3(id); //部分
                billOutSapService.updateBillInSapState3(id); //部分
            }else {
                billOutSapService.updateBillInMasterState2(id); //已过账
                billOutSapService.updateBillInSapState2(id); //已过账
            }
        }
        ExcelUtil<BillOutSapDetailVo> util = new ExcelUtil<>(BillOutSapDetailVo.class);
        return util.exportExcel(byIds, "SAP出库过账单据");
    }

}
